package seedbed_allocation_record

import (
	rich_err "app/error"
	"app/models"
	"app/service"
	"app/service/greenhouse_allocation_record"
	"app/service/orders"
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"math"
	"strconv"
	"time"

	"github.com/jinzhu/gorm"

	"github.com/gin-gonic/gin"
)

func Gets(context *gin.Context) ([]*models.SeedbedAllocationRecordDetail, *models.Pager, *rich_err.RichError) {
	base := models.Orm.Model(&models.SeedbedAllocationRecord{}).
		Select("seedbed_allocation_record.*, orders.name as orders_name,  greenhouse.name as greenhouse_name, seedbed.name as seedbed_name, seedbed.area as seedbed_area").
		Joins("LEFT JOIN orders ON seedbed_allocation_record.order_id = orders.id").
		Joins("LEFT JOIN greenhouse ON seedbed_allocation_record.greenhouse_id = greenhouse.id").
		Joins("LEFT JOIN seedbed ON seedbed_allocation_record.seedbed_id = seedbed.id")

	results, pager, err := service.GetDetails[models.SeedbedAllocationRecordDetail](context, base, models.SeedbedAllocationRecord{}.TableName(), map[string]string{"orders_name": "orders.name", "greenhouse_name": "greenhouse.name", "seedbed_area": "seedbed.area"})

	if err != nil {
		return nil, nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return results, pager, nil
}

func Get(id string) (*models.SeedbedAllocationRecordDetail, *rich_err.RichError) {
	base := models.Orm.Model(&models.SeedbedAllocationRecord{}).
		Select("seedbed_allocation_record.*, orders.name as orders_name,  greenhouse.name as greenhouse_name, seedbed.name as seedbed_name").
		Joins("LEFT JOIN orders ON seedbed_allocation_record.order_id = orders.id").
		Joins("LEFT JOIN greenhouse ON seedbed_allocation_record.greenhouse_id = greenhouse.id").
		Joins("LEFT JOIN seedbed ON seedbed_allocation_record.seedbed_id = seedbed.id")

	result, err := service.GetDetail[models.SeedbedAllocationRecordDetail](id, base)

	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return result, nil
}

func Create(context *gin.Context) (*models.SeedbedAllocationRecordDetail, *rich_err.RichError) {
	bodyBytes, err := ioutil.ReadAll(context.Request.Body)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	// 重新写入原始数据到 context.Request.Body 中
	context.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))

	req := new(models.SeedbedAllocationRecordCore)
	err = json.Unmarshal(bodyBytes, req)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}

	// 判断唯一索引是否存在,存在的话,直接换成update
	var exited models.SeedbedAllocationRecord
	models.Orm.Table("seedbed_allocation_record").Select("id").Where("greenhouse_id = ? and greenhouse_allocation_id = ? and seedbed_id = ?", req.GreenhouseID, req.GreenhouseAllocationID, req.SeedbedID).First(&exited)

	if exited.ID > 0 {
		dateTimeNow := time.Now().Format("2006-01-02 15:04:05")
		remark := exited.Remark + "; " + dateTimeNow + " 新增: " + strconv.Itoa(req.Quantity)
		context.AddParam("id", strconv.Itoa(exited.ID))
		return Update(context, remark)
	}

	data := models.SeedbedAllocationRecord{SeedbedAllocationRecordCore: *req}
	if data.Quantity == 0 {
		data.Quantity = data.TrayNumber * data.UnitNumber
	}
	result := models.Orm.Create(&data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	err = orders.UpdateAllocatedSeedbedQuantity(req.OrderID)
	if err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	err = greenhouse_allocation_record.UpdateAllocatedSeedbedQuantity(data.GreenhouseAllocationID)
	if err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	// 更新订单成已分苗床
	if err := models.Orm.Model(&models.Orders{}).Where("id = ?", req.OrderID).Update("order_status", 7).Error; err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	return Get(strconv.Itoa(data.ID))
}

func Update(context *gin.Context, remark string) (*models.SeedbedAllocationRecordDetail, *rich_err.RichError) {
	req := new(models.SeedbedAllocationRecordDelta)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}

	data, err := service.Get[models.SeedbedAllocationRecord](context)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	if req.TrayNumber != nil {
		data.TrayNumber = int(math.Round(req.TrayNumber.(float64)))
	}
	if req.UnitNumber != nil {
		data.UnitNumber = int(math.Round(req.UnitNumber.(float64)))
	}
	if req.Quantity != nil {
		data.Quantity = int(math.Round(req.Quantity.(float64)))
	} else {
		data.Quantity = data.TrayNumber * data.UnitNumber
	}
	if req.GreenhouseID != nil {
		data.GreenhouseID = int(math.Round(req.GreenhouseID.(float64)))
	}
	if req.SeedbedID != nil {
		data.SeedbedID = int(math.Round(req.SeedbedID.(float64)))
	}
	if req.GreenhouseAllocationID != nil {
		data.GreenhouseAllocationID = int(math.Round(req.GreenhouseAllocationID.(float64)))
	}
	if req.OrderID != nil {
		data.OrderID = int(math.Round(req.OrderID.(float64)))
	}
	if req.Remark != nil {
		data.Remark = req.Remark.(string)
	}
	if remark != "" {
		data.Remark = remark
	}
	result := models.Orm.Save(data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	err = orders.UpdateAllocatedSeedbedQuantity(data.OrderID)
	if err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	err = greenhouse_allocation_record.UpdateAllocatedSeedbedQuantity(data.GreenhouseAllocationID)
	if err != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	return Get(strconv.Itoa(data.ID))
}

func Delete(context *gin.Context) *rich_err.RichError {
	data, err := service.Get[models.SeedbedAllocationRecord](context)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil
		}
		return rich_err.NewError(rich_err.RequestInvalid, err)
	}
	result := models.Orm.Delete(data)
	if result.Error != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	err = orders.UpdateAllocatedSeedbedQuantity(data.OrderID)
	if err != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	err = greenhouse_allocation_record.UpdateAllocatedSeedbedQuantity(data.GreenhouseAllocationID)
	if err != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	return nil
}
